package com.example.second.controller;

import com.alibaba.fastjson.JSON;
import com.example.second.service.IStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ReactiveRedisOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
public class StockController {

    @Autowired
    IStockService iStockService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/getstocklist")
    public Map<String, Object> getStockList(){
        return iStockService.getStockList();
    }

    @RequestMapping("/getstock/{sku_id}")
    public Map<String,Object> getStock(@PathVariable String sku_id){
        return iStockService.getStock(sku_id);
    }

    @RequestMapping("/insertlimitpolicy/{json}")
    public Map<String,Object> insertLimitPolicy(@PathVariable String json, HttpServletRequest httpServletRequest){
        HashMap<String, Object> resultMap = new HashMap<>();
        String user_id = "";
        if (httpServletRequest.getCookies()!=null){
            for( Cookie cookie:httpServletRequest.getCookies()){
                String sessionid = cookie.getValue();
                String session = stringRedisTemplate.opsForValue().get(sessionid);
                if(session==null){
                    continue;
                }
                Map<String,Object> usermap = JSON.parseObject(stringRedisTemplate.opsForValue().get(sessionid), Map.class);

                if(usermap!=null&&!usermap.isEmpty()&&usermap.get("user_id")!=null&&usermap.get("user_role")!=null&&usermap.get("user_role").equals("1")){
                    user_id = usermap.get("user_id").toString();
                    break;
                }
            }
        }
        if (user_id.equals("")){
            resultMap.put("result", false);
            resultMap.put("msg","qingxiandenglu" );
            return resultMap;
        }

        Map<String,Object>  policy = JSON.parseObject(json,Map.class);
        return iStockService.insertLimitPolicy(policy);
    }
}
